package org.nowcoder.huawei.other;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
import java.util.stream.Collectors;

/**
 * HJ68: 成绩排序
 */
public class HJ68 {
    static class Student {
        private String name;
        private int score;

        public Student(String name, int score) {
            this.name = name;
            this.score = score;
        }

        public int getScore() {
            return score;
        }

        @Override
        public String toString() {
            return name + " " + score;
        }
    }

    public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
            int n = Integer.parseInt(br.readLine());
            int flag = Integer.parseInt(br.readLine());
            int count = 0;
            List<Student> students = new ArrayList<>();

            while (count < n) {
                String[] vars = br.readLine().split(" ");
                students.add(new Student(vars[0], Integer.parseInt(vars[1])));
                count++;
            }

            if (0 == flag) { // 降序排序
                students = students.stream()
                        .sorted(Comparator.comparing(Student::getScore).reversed())
                        .collect(Collectors.toList());
            } else {
                students = students.stream() // 默认升序排序
                        .sorted(Comparator.comparing(Student::getScore))
                        .collect(Collectors.toList());
            }
            students.forEach(System.out::println);
        } catch (IOException e) {
            //throw new RuntimeException(e);
        }
    }
}
